#serialCommu.py
#coding: utf-8
import sys, re, time
import platform
import threading
import logging
import serial
from serial.tools import list_ports

class SerialTool(object):
    """docstring for ClassName"""
    def __init__(self):
        super(SerialTool, self).__init__()
        self.ser_selected = None
        self.config = dict()
        self.isalive = False
        self.recv_count = 0
        self.recv_data = ""
        self.recv_maxlen = 255

        self.ser_list = list()
        self.get_all_serials()


    def get_all_serials(self):
        if platform.system() == "Windows":
            try:
                for com in list_ports.comports():
                    self.ser_list.append(com)
            except Exception as e:
                logging.error(e)

    def open(self, Port="/dev/ttyUSB0", BaudRate="115200", ByteSize="8", Parity="N", Stopbits="1"):

        self.config['port'] = Port
        self.config['baudrate'] = int(BaudRate)
        self.config['bytesize'] = int(ByteSize)
        self.config['parity'] = Parity
        self.config['stopbits'] = int(Stopbits)
        self.config['timeout'] = 1

        self.ser_selected = serial.Serial()
        self.ser_selected.port = self.config['port']
        self.ser_selected.baudrate = self.config['baudrate']
        self.ser_selected.bytesize = self.config['bytesize']
        self.ser_selected.parity = self.config['parity']
        self.ser_selected.stopbits = self.config['stopbits']
        self.ser_selected.timeout = self.config['timeout']

        try:
            self.ser_selected.open()
            if self.ser_selected.isOpen():
                self.isalive = True
        except Exception as e:
            self.isalive = False
            logging.error(e)
            print e

    def close(self):
        if self.ser_selected.isOpen():
            self.ser_selected.close()
        self.isalive = False

    def read(self):
        while self.isalive:
            try:
                number = self.ser_selected.inWaiting()
                if number:
                    self.recv_data += self.ser_selected.read(number)#.replace(binascii.unhexlify("00"), "")
                    # print number
                    if self.recv_maxlen <= len(self.recv_data):
                        self.recv_data = ""
            except Exception as e:
                logging.error(e)

    def write(self, data, isStr):

        if self.isalive:
            if self.ser_selected.isOpen():
                buf = data
                if isStr is not True:
                    buf = ""
                    for i in data:
                        buf += chr(i)
                return self.ser_selected.write(buf)

def test():
    port_list = list(list_ports.comports())
    print len(port_list)
    for i in range(len(port_list)):
        print port_list[0], port_list[0][1]

    for com in list_ports.comports():
        print com[0]

    com = None
    ser = SerialTool()
    for i in ser.ser_list:
        print i[0], i[1]
        print i[1].find("Prolific")
        if i[1].find("Prolific") >= 0:
            com = i[0]
    print ser.config
    print ser.isalive
    print com
    if com is None:
        ser.open()
    else:
        ser.open(port=com)
    print ser.isalive

    if ser.isalive:
        thread_read_com = threading.Thread(target=ser.read)
        thread_read_com.setDaemon(True)
 #       thread_read_com.start()

    str = "test.. hello, world!!!\n"
    print "send len: %d" %(len(str))

    for i in range(10):
        send_len = ser.write(str)
        if len(str) != send_len:
            print "wish send %d, actual send: %d" %(len(str), send_len)
        time.sleep(0.1)
        print ser.recv_data
        print ser.recv_count
        
    ser.close()   

if __name__ == '__main__':
    test()
